#include "ShadowMapper.h"

#include <fstream>

ShadowMapper::ShadowMapper(Framebuffer *framebuffer, int width, int height)
{
	this ->framebuffer = framebuffer;

	this ->texWidth = width;
	this ->texHeight = height;

	shadowTex = new DepthTexture(width, height);
	colorTex = new Texture(width, height, 32, NULL);
}

ShadowMapper::~ShadowMapper(void)
{
	if (shadowTex != NULL)
		delete shadowTex;

	if (colorTex != NULL)
		delete colorTex;
}

UINT ShadowMapper::GetShadowMap(sm::Vec3 lightPosition, sm::Vec3 lightTarget, IRenderable *renderable)
{
	glPushAttrib(GL_ENABLE_BIT);

	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDisable(GL_TEXTURE_2D);

	Camera cam(0, 0);
	cam.SetPosition(lightPosition);
	cam.SetLookTarget(lightTarget);
	
	glViewport(0, 0, texWidth, texHeight);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluPerspective(60.0f, (float)texWidth / (float)texHeight, 0.1f, 1000.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	//camera ->SetViewMatrix();
	cam.SetViewMatrix();

	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);
	framebuffer ->AttachColorTexture(colorTex ->GetId());
	framebuffer ->AttachDepthTexture(shadowTex ->GetId());
	framebuffer ->StartRenderToTexture();

	glClear(GL_DEPTH_BUFFER_BIT);

	//float data[65536];
	//glBindTexture(GL_TEXTURE_2D, shadowTex ->GetId());

	//glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);

	renderable ->Render();

	/*glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);

	std::ofstream file("c:\\cipa.txt");
	int line = 0;
	for (int i = 0; i < 256 * 256; i++)
	{
		if ((i % 256) == 0)
			file << "\n";

		if (data[i] == 1.0f)
			file << "1";
		else
			file << "0";
	}
	file.close();*/

	framebuffer ->FinishRenderToTexture();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);

	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

	glPopAttrib();
	glViewport(0, 0, 1280, 1024);

	glDrawBuffer(GL_BACK);
	glReadBuffer(GL_BACK);

	return shadowTex ->GetId();
	//return colorTex ->GetId();
}
